/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.news.server.handlers.meta;

import cn.ac.iie.di.ban.news.server.util.HostInfoKeeper;
import cn.ac.iie.di.ban.news.server.util.KeyInfoKeeper;
import cn.ac.iie.di.commons.httpserver.framework.handler.HandlerI;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;

/**
 *
 * @author zwlin
 */
public class DispatchHandler implements HandlerI {

	private static HostInfoKeeper hostKeeper = null;
	private static KeyInfoKeeper keyKeeper = null;

	public static void init(HostInfoKeeper hostInfoKeeper, KeyInfoKeeper keyInfoKeeper) {
		DispatchHandler.hostKeeper = hostInfoKeeper;
		DispatchHandler.keyKeeper = keyInfoKeeper;
	}

	@Override
	public void init() throws Exception {
		if (hostKeeper == null || keyKeeper == null) {
			throw new Exception("hostKeepr or keyKeeper not set.");
		}
	}

	@Override
	public void execute(Request pRequest, HttpServletRequest request, HttpServletResponse response) throws Exception {
//		String ips = "192.168.11.95\n"
//				+ "192.168.11.96\n"
//				+ "192.168.11.97";
//		response.getWriter().print(ips);
		String key = request.getParameter("key");
		if (key == null || key.trim().isEmpty()) {
			response.sendError(HttpServletResponse.SC_BAD_REQUEST, "param key not exist.");
			return;
		}
		key = key.trim();
		if (keyKeeper.isOnline(key)) {
//			if (!keyKeeper.isActivated(key)) {
//				response.sendError(HttpServletResponse.SC_BAD_REQUEST,
//						"key not activated for online data load.");
//				return;
//			}
			response.getWriter().append(hostKeeper.getOnlineHostLines()).flush();
		} else if (keyKeeper.isTest(key)) {
//			if (!keyKeeper.isActivated(key)) {
//				response.sendError(HttpServletResponse.SC_BAD_REQUEST,
//						"key not activated for test data load.");
//				return;
//			}
			response.getWriter().append(hostKeeper.getTestHostLines()).flush();
		} else {
			response.sendError(HttpServletResponse.SC_BAD_REQUEST,
					"key not valid.");
			return;
		}
		response.setStatus(HttpServletResponse.SC_OK);
	}

}
